/*
 *  CanvasiPhoneGL.mm
 *  SypX
 *
 *  Created by Luv Khemani on 5/7/10.
 *  Copyright 2010 Luv Khemani. All rights reserved.
 *
 */

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#include <iostream>
#include "CanvasiPhoneGL.h"
#include "SypXAppDelegate.h"
#include "Engine.h"

namespace SypX
{	
	GLView* CanvasIPhoneGL::view = 0;
	UIWindow* CanvasIPhoneGL::window = 0;

	CanvasIPhoneGL::CanvasIPhoneGL():Canvas()
	{
		pool = [[NSAutoreleasePool alloc] init];
	}
	
	CanvasIPhoneGL::~CanvasIPhoneGL()
	{
		[pool release];				
	}
	
	void CanvasIPhoneGL::init()
	{
		//Always fullscreen on iPhone
		CGRect screenBounds = [[UIScreen mainScreen] bounds];//retrieve screen size	
		unsigned int w,h;
		w = screenBounds.size.width;
		h = screenBounds.size.height;
		//resize(w,h);	
		resize(320, 480);
		lastTime = CACurrentMediaTime();
		UIApplicationMain(0, 0, nil, @"SypXAppDelegate");		
	}
	
	void CanvasIPhoneGL::swapBuffers()
	{		
		[view swapBuffers];//SwapBuffers
		
	}	
	void CanvasIPhoneGL::registerWindowView(GLView* v, UIWindow* win )
	{
		view = v;
		window = win;	
	
	}
	
	bool CanvasIPhoneGL::isOpen()
	{
		return true;	//Its always true on IPhone cos there is no multitasking
	}
	

	bool CanvasIPhoneGL::hasEvents()
	{
		std::deque<Event>* events = [view getEventList];
		if(events->empty())
		{
			return false;
		}
		else 
		{
			return true;
		}
	}
	
	float CanvasIPhoneGL::getElapsedTime()
	{
		CFTimeInterval time = CACurrentMediaTime();
		CFTimeInterval t = time - lastTime;
		lastTime = time;
		return static_cast<float> (t);
	}
	
	Event CanvasIPhoneGL::getEvent()
	{
		std::deque<Event>* events = [view getEventList];
		Event e;
		
		if (events->empty()) 
		{
			e.type = NOEVENTS;
		}
		else 
		{
			e = events->front();
			events->pop_front();
		}
		return e;
	}

}